﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using SDSystem.Models;
using ComboBox = Ext.Net.ComboBox;
using MessageBox = Ext.Net.MessageBox;

namespace SDSystem.Controllers
{
    [DirectController]
    public class ForumController : Controller
    {
        //
        // GET: /Forum/
        private ForumEntities db=new ForumEntities();



        #region Forum

        public ActionResult Index()
        {
            Session["sForumName"] = "";
            return View();
        }

        //Search Forum
        public ActionResult Search()
        {
            var store = X.GetCmp<Store>("ForumDataStore");
            Session["sForumName"] = X.GetCmp<TextField>("txtForumName").Text;
            Session["sCateName"] = X.GetCmp<TextField>("txtCateName").Text;
            Session["sTypeName"] = X.GetCmp<TextField>("txtTypeName").Text;
            Session["sForumDescription"] = X.GetCmp<TextField>("txtForumDescription").Text;
            store.Reload();
            return this.Direct();
        }

        public ActionResult ClearSearch()
        {
            var store = X.GetCmp<Store>("ForumDataStore");
            Session["sForumName"] = X.GetCmp<TextField>("txtForumName").Text="";
            Session["sCateName"] = X.GetCmp<TextField>("txtCateName").Text="";
            Session["sTypeName"] = X.GetCmp<TextField>("txtTypeName").Text="";
            Session["sForumDescription"] = X.GetCmp<TextField>("txtForumDescription").Text="";
            store.Reload();
            return this.Direct();
        }

        //Create Forum
        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.CateList = new List<ListItem>();
            ViewBag.CateList =
                db.Categories.ToList().Select(e => new ListItem {Text = e.CateName, Value = e.CateId.ToString()});
            ViewBag.TypeList = new List<ListItem>();
            ViewBag.TypeList =
                db.ForumTypes.ToList().Select(e => new ListItem {Text = e.TypeName, Value = e.ForumTypeId.ToString()});
            ViewBag.DateCreate = DateTime.Now.Date;
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Forum fr)
        {
            
            //fr.CateId = Convert.ToInt32(X.GetCmp<ComboBox>("listCate").SelectedItem.Value);
            //fr.TypeId = Convert.ToInt32(X.GetCmp<ComboBox>("listType").SelectedItem.Value);
            //fr.IsActive = X.GetCmp<Checkbox>("forumActive").Checked;
            
            if (ModelState.IsValid)
            {
                fr.TotalTopics = 0;
                fr.TotalMembers = 0;
                fr.CateId = Convert.ToInt32(fr.CateId);
                fr.TypeId = Convert.ToInt32(fr.TypeId);
                fr.IsActive = true;
                db.Fora.AddObject(fr);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Create Service success!").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed!!!", "Create Service non success!").Show();
            return this.FormPanel();
        }

        //Edit Forum
        public ActionResult Edit(int id)
        {
            Forum fr = db.Fora.FirstOrDefault(e => e.ForumId == id);
            ViewBag.CateList = new List<ListItem>();
            ViewBag.CateList =
                db.Categories.ToList().Select(e => new ListItem { Text = e.CateName, Value = e.CateId.ToString() });
            ViewBag.TypeList = new List<ListItem>();
            ViewBag.TypeList =
                db.ForumTypes.ToList().Select(e => new ListItem { Text = e.TypeName, Value = e.ForumTypeId.ToString() });
            ViewBag.Cate = fr.CateId.ToString();
            ViewBag.Type = fr.TypeId.ToString();
            ViewBag.CheckActive = fr.IsActive;
            return View(fr);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditCommit(Forum fr)
        {
            Forum fr1 = db.Fora.SingleOrDefault(e => e.ForumId == fr.ForumId);
            if(ModelState.IsValid)
            {
                //fr.CateId = Convert.ToInt32(X.GetCmp<ComboBox>("listCate").SelectedItem.Value);
                //fr.TypeId = Convert.ToInt32(X.GetCmp<ComboBox>("listType").SelectedItem.Value);
                //fr.IsActive = X.GetCmp<Checkbox>("forumActive").Checked;
                fr.CateId = Convert.ToInt32(fr.CateId);
                fr.TypeId = Convert.ToInt32(fr.TypeId);
                db.Fora.Detach(fr1);
                db.Fora.Attach(fr);
                db.ObjectStateManager.ChangeObjectState(fr, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Edit forum success!").Show();
            }
            return this.FormPanel();
        }

        //Binding Data
        public ActionResult ForumData(StoreRequestParameters parameters)
        {
            string forumname = (String) Session["sForumName"];
            string catename=(String)Session["sCateName"];
            string typename = (String)Session["sTypeName"];
            string forumdescription = (String) Session["sForumDescription"];
            var result = (from forum in db.Fora
                          join category in db.Categories on forum.CateId equals category.CateId

                          join forumType in db.ForumTypes on forum.TypeId equals forumType.ForumTypeId

                          select new
                          {
                              forum.ForumId,
                              forum.ForumName,
                              forumType.TypeName,
                              category.CateName,
                              forum.Description,
                              forum.DateCreate,
                              forum.IsActive
                          }).Where(e=>(string.IsNullOrEmpty(forumname) || e.ForumName.Contains(forumname)) &&
                                      (string.IsNullOrEmpty(catename) || e.CateName.Contains(catename)) &&
                                      (string.IsNullOrEmpty(typename) || e.TypeName.Contains(typename)) &&
                                      (string.IsNullOrEmpty(forumdescription) || e.Description.Contains(forumdescription)));

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.ForumId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());

        }
        #endregion

        #region Category
        //List Category
        public ActionResult ListCategory()
        {
            return View();
        }

        //Create new Category
        public ActionResult CreateCategory()
        {
            ViewBag.DateCreate = DateTime.Now.Date;
            return View();
        }
        
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateCategory(Category cate)
        {
            if(ModelState.IsValid)
            {
                var tmpCateName = cate.CateName;
                int countCateName = db.Categories.Count(e => e.CateName == tmpCateName);
                if (countCateName > 0)
                {
                    X.Msg.Alert("Error", "Category Name is used!Please,Try again").Show();
                    //X.Msg.Confirm("Confirm","Service Name is used!").Show();
                    return this.FormPanel();
                }
                db.Categories.AddObject(cate);
                db.SaveChanges();
                X.Msg.Notify("Success", "Create Category Successfull").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Success", "Create Failed!!!").Show();
            return this.FormPanel();
        }

        //Edit Category
        public ActionResult EditCategory(int id)
        {
            Category cateDb = db.Categories.SingleOrDefault(e => e.CateId == id);
            return View(cateDb);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditCategory(Category cate)
        {
            Category cate1 = db.Categories.SingleOrDefault(e => e.CateId == cate.CateId);
            if(ModelState.IsValid)
            {
                var tmpCateName = cate.CateName;
                var tmpCateId = cate.CateId;
                int countCateName = db.Categories.Where(e=>e.CateId!=tmpCateId).Count(e => e.CateName == tmpCateName);
                if (countCateName > 0)
                {
                    X.Msg.Alert("Error", "Category Name is used!Please,Try again").Show();
                    //X.Msg.Confirm("Confirm","Service Name is used!").Show();
                    return this.FormPanel();
                }
                db.Categories.Detach(cate1);
                db.Categories.Attach(cate);
                db.ObjectStateManager.ChangeObjectState(cate, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Success", "Save Category Successfull").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Success", "Save Failed!!!").Show();
            return this.FormPanel();
        }

        //Data Category
        public ActionResult CategoryData(StoreRequestParameters parameters)
        {
            var result = from categoryDB in db.Categories
                         select new
                                    {
                                        categoryDB.CateId,
                                        categoryDB.CateName,
                                        categoryDB.Description,
                                        categoryDB.DateCreate,
                                        categoryDB.OrderBy
                                    };
            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.CateId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());
        }
        #endregion

        #region ForumType

        //List Forum Type
        public ActionResult ListForumType()
        {
            return View();
        }

        //Create new Forum Type
        public ActionResult CreateForumType()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateForumType(ForumType ftype)
        {
            if (ModelState.IsValid)
            {
                var tmpTypeName = ftype.TypeName;
                int countTypeName = db.ForumTypes.Count(e => e.TypeName == tmpTypeName);
                if (countTypeName > 0)
                {
                    X.Msg.Alert("Error", "Forum Type Name is used!Please,Try again").Show();
                    //X.Msg.Confirm("Confirm","Service Name is used!").Show();
                    return this.FormPanel();
                }
                db.ForumTypes.AddObject(ftype);
                db.SaveChanges();
                X.Msg.Notify("Success", "Create Forum Type Successfull").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Success", "Create Failed!!!").Show();
            return this.FormPanel();
        }

        //Edit Forum Type
        public ActionResult EditForumType(int id)
        {
            ForumType ftypeDb = db.ForumTypes.SingleOrDefault(e => e.ForumTypeId == id);
            return View(ftypeDb);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditForumType(ForumType ftype)
        {
            ForumType ftype1 = db.ForumTypes.SingleOrDefault(e => e.ForumTypeId == ftype.ForumTypeId);
            if (ModelState.IsValid)
            {
                var tmpFTypeName = ftype.TypeName;
                var tmpFTypeId = ftype.ForumTypeId;
                int countFTypeName = db.ForumTypes.Where(e => e.ForumTypeId != tmpFTypeId).Count(e => e.TypeName == tmpFTypeName);
                if (countFTypeName > 0)
                {
                    X.Msg.Alert("Error", "Forum Type Name is used!Please,Try again").Show();
                    //X.Msg.Confirm("Confirm","Service Name is used!").Show();
                    return this.FormPanel();
                }
                db.ForumTypes.Detach(ftype1);
                db.ForumTypes.Attach(ftype);
                db.ObjectStateManager.ChangeObjectState(ftype, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Success", "Save Forum Type Successfull").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Success", "Save Failed!!!").Show();
            return this.FormPanel();
        }

        //Data Forum Type
        public ActionResult ForumTypeData(StoreRequestParameters parameters)
        {
            var result = from forumType in db.ForumTypes
                         select new
                                    {
                                        forumType.ForumTypeId,
                                        forumType.TypeName,
                                        forumType.Description
                                    };
            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.ForumTypeId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());
        }
        #endregion

    }
}
